package org.derusse.cycle.activity;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import org.derusse.cycle.CycleMeterApplication;
import org.derusse.cycle.R;
import org.derusse.cycle.database.TrackTable;
import org.derusse.cycle.model.Tools;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.AdapterView.OnItemClickListener;

public class TrackHistoryActivity extends Activity implements OnItemClickListener
{
	private CycleMeterApplication application;

	private ArrayList<HashMap<String, String>> trackListData;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		this.setContentView(R.layout.track_history);

		this.application = (CycleMeterApplication) getApplication();

		
		trackListData = new ArrayList<HashMap<String, String>>();

		Cursor cursor = null;
		SQLiteDatabase db = null;
		try
		{
			db = this.application.getDatabaseHelper().getReadableDatabase();
			cursor = TrackTable.List(db);

			if (cursor != null)
			{
				if (cursor.moveToFirst())
				{
					Date d = new Date();
					do
					{
						d.setTime(cursor.getLong(3));
						HashMap<String, String> map = new HashMap<String, String>();
						map.put("id", cursor.getString(0));
						map.put("distance", Tools.StringifyDistance(cursor.getDouble(1)));
						map.put("time", Tools.StringifyElaps(cursor.getLong(3), cursor.getLong(4)));
						map.put("date", d.toLocaleString());
						trackListData.add(map);

						cursor.moveToNext();
					} while (!cursor.isLast());
				}
			}
		} finally
		{
			cursor.close();
			db.close();
		}

		SimpleAdapter mSchedule = new SimpleAdapter(this, trackListData, R.layout.list_item, new String[]
		{ "date", "distance", "time" }, new int[]
		{ R.id.ListItemDate, R.id.ListItemDistance, R.id.ListItemTime });

		ListView trackList = (ListView) findViewById(R.id.TrackHistoryList);
		trackList.setAdapter(mSchedule);
		trackList.setOnItemClickListener(this);
	}

	public void onItemClick(AdapterView<?> parent, View v, int position, long id)
	{
		HashMap<String, String> row = this.trackListData.get(position);
		this.application.trackView = Long.parseLong(row.get("id"));

		Intent intent = new Intent(TrackHistoryActivity.this, TrackViewerActivity.class);
		startActivity(intent);

	}
}